package Controller;

import Service.NewsService;
import Util.Category;
import com.example.SSMDemo.Entity.News;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
新闻主页
 */
@Controller
@WebServlet(name = "MainNewsServlet")
public class MainNewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        NewsService newsService=new NewsService();
        try {
            List<News> lsNews=newsService.QueryNews();
            List<List<News>> lsNews_by_category= new ArrayList<>();
            for (int i = 0; i <Category.values().length ; i++) {
                List<News> temp=new ArrayList<>();
                lsNews_by_category.add(temp);
            }
            for (News news:lsNews) {
                if (news.getCategory().equals("图片新闻") && lsNews_by_category.get(0).size()<6)
                    lsNews_by_category.get(0).add(news);
                else if (news.getCategory().equals("学术交流") && lsNews_by_category.get(1).size()<6)
                    lsNews_by_category.get(1).add(news);
                else if (news.getCategory().equals("新闻速递") && lsNews_by_category.get(2).size()<6)
                    lsNews_by_category.get(2).add(news);
                else if (news.getCategory().equals("党建动态") && lsNews_by_category.get(3).size()<6)
                    lsNews_by_category.get(3).add(news);
                else if (news.getCategory().equals("通知公告") && lsNews_by_category.get(4).size()<6)
                    lsNews_by_category.get(4).add(news);
                else if (news.getCategory().equals("专题列表") && lsNews_by_category.get(5).size()<6)
                    lsNews_by_category.get(5).add(news);
            }
            request.setAttribute("lsNews_by_0",lsNews_by_category.get(0));
            request.setAttribute("lsNews_by_1",lsNews_by_category.get(1));
            request.setAttribute("lsNews_by_2",lsNews_by_category.get(2));
            request.setAttribute("lsNews_by_3",lsNews_by_category.get(3));
            request.setAttribute("lsNews_by_4",lsNews_by_category.get(4));
            request.setAttribute("lsNews_by_5",lsNews_by_category.get(5));
            request.getRequestDispatcher("SWPUnews.jsp").forward(request,response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
